//
//  HMNetworkTools.swift
//  weibo
//
//  Created by 杨念川 on 16/9/5.
//  Copyright © 2016年 杨念川. All rights reserved.
//

import UIKit
import AFNetworking
//定义一个请求的枚举
enum HTTPMethod: String {
    case Get = "GET"
    case Post = "POST"
}
class HMNetworkTools: AFHTTPSessionManager {
    //创建一个单例
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        //添加支持解析的类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        return tools
    }()
    // 将回调数据的闭包定义成一个别名
    typealias HMRequestCallBack = @escaping (Any?, Error?) -> ()
    //网络请求
    func request(method: HTTPMethod, urlString: String, parameters: Any?, completion:HMRequestCallBack)  {
        let successClosure: (URLSessionDataTask, Any?) -> () = {(_ ,responseObject) in
            //请求成功的回调
            completion(responseObject,nil)
        }
        let failureClosure: (URLSessionDataTask?, Error) -> () = { (_, error) in
            // 请求失败的回调
            completion(nil, error)
        }
        //根据不同的方式发送请求
        if method == .Get {
            self.get(urlString, parameters: parameters, progress: nil, success: successClosure, failure: failureClosure)
        }else {
            self.post(urlString, parameters: parameters, progress: nil, success: successClosure, failure: failureClosure)
        }
    }

}
